import React, { Component, createRef } from 'react'

import styles from './index.module.css'

import PropTypes from 'prop-types'

export default class Sticky extends Component {
  // 创建ref对象
  placeHolder = createRef()
  content = createRef()

  handleScroll = () => {
    // 获取DOM对象
    const placeHolderEl = this.placeHolder.current
    const contentEl = this.content.current

    const { top } = placeHolderEl.getBoundingClientRect()
    
    if (top < 0) {
      contentEl.classList.add(styles.fixed)
      // 防止在页面top小于0的瞬间发生跳动
      placeHolderEl.style.height = this.props.height + 'px'
    } else {
      contentEl.classList.remove(styles.fixed)
      placeHolderEl.style.height = '0px'
    }
  }

  // 监听scroll事件
  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll)
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll)
  }

  render() {
    return (
      <div>
        {/* 占位元素 */}
        <div ref={this.placeHolder}></div>
        {/* 内容元素 */}
        <div ref={this.content}>{this.props.children}</div>
      </div>
    )
  }
}

Sticky.propTypes = {
  height: PropTypes.number.isRequired
}